package ai

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/dn-jinmin/chatcms/internal/logic/ai/base"
	"gitee.com/dn-jinmin/chatcms/internal/svc"
	"gitee.com/dn-jinmin/langchaingo"
	"github.com/tmc/langchaingo/prompts"
)

type Answer struct {
	svc *svc.ServiceContext
	*base.Base
}

func NewAnswer(svc *svc.ServiceContext) *Answer {
	prompt := prompts.NewPromptTemplate(AnswerPrompt, []string{"input", "think", "reference"})
	return &Answer{
		svc:  svc,
		Base: base.NewBase(svc, prompt),
	}
}

func (a *Answer) Name() string {
	return "answer"
}

func (a *Answer) Description() string {
	return `
根据用户问题，生成符合要求的话术
需求参数 以json格式提供
{
	"input": "用户问题",
	"reference": "参考信息"
}
`
}

type Params struct {
	Input     string `json:"input"`
	Reference string `json:"reference"`
}

func (a *Answer) Call(ctx context.Context, input string) (string, error) {
	fmt.Println(input)
	// 解析参数
	var params Params
	if err := json.Unmarshal([]byte(input), &params); err != nil {
		return "", err
	}

	// 调用模型
	output, err := a.Base.Call(ctx, map[string]any{
		"input":     params.Input,
		"think":     "",
		"reference": params.Reference,
	})
	if err != nil {
		return "", err
	}

	return output[langchaingo.OutPutKey].(string), nil
}
